import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { TOGGLE_COLLAPSE, TOGGLE_PANE, SET_NAV_STAGE } from '../constants';

const initalState = {
  isCollapse: false,
  showPane: false,
  navStage: 'main', // main sub
};

// isCollapse
export function toggleCollapse() {
  return {
    type: TOGGLE_COLLAPSE,
  };
}
export function useToggleCollapse() {
  const dispatch = useDispatch();
  const isCollapse = useSelector((state) => state.app.isCollapse);
  const boundAction = useCallback(() => dispatch(toggleCollapse()), [dispatch]);
  return { isCollapse, toggleCollapse: boundAction };
}
export function isCollapse(state, action) {
  switch (action.type) {
    case TOGGLE_COLLAPSE:
      return {
        ...state,
        isCollapse: !state.isCollapse,
      };
    default:
      break;
  }
  return state;
}

// showPane
export function togglePane(open) {
  return {
    type: TOGGLE_PANE,
    open,
  };
}
export function useTogglePane() {
  const dispatch = useDispatch();
  const showPane = useSelector((state) => state.app.showPane);
  const boundAction = useCallback((open) => dispatch(togglePane(open)), [dispatch]);
  return { showPane, togglePane: boundAction };
}
export function showPane(state, action) {
  switch (action.type) {
    case TOGGLE_PANE:
      return {
        ...state,
        showPane: action.open,
      };
    default:
      break;
  }
  return state;
}

// navStage
export function setNavStage(navStage) {
  return {
    type: SET_NAV_STAGE,
    navStage,
  };
}
export function useNavStage() {
  const dispatch = useDispatch();
  const navStage = useSelector((state) => state.app.navStage);
  const boundAction = useCallback((navStage) => dispatch(setNavStage(navStage)), [dispatch]);
  return { navStage, setNavStage: boundAction };
}
export function navStage(state, action) {
  switch (action.type) {
    case SET_NAV_STAGE:
      return {
        ...state,
        navStage: action.navStage,
      };
    default:
      break;
  }
  return state;
}

const reducers = [isCollapse, showPane, navStage];

export default function reducer(state = initalState, action) {
  let newState;
  switch (action.type) {
    // Handle cross-topic actions here
    default:
      newState = state;
      break;
  }
  return reducers.reduce((s, r) => r(s, action), newState);
}
